package com.ccys.db.page;

import com.github.pagehelper.PageHelper;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Data
public class PageDto {
    private Integer offset;
    private Integer limit;
    private Integer pageNum;
    private Integer pageSize;
    private Boolean countSql = true;
    private String orderBy = null;
    private Boolean reasonable = false;
    private Boolean pageSizeZero = true;

    public static PageDto getPage(HttpServletRequest request) {
        PageDto pageDto = new PageDto();
        if (request == null) {
            pageDto.setPageNum(1);
        }
        pageDto.setPageSize(10);
        pageDto.setPageNum(StringUtils.isBlank(request.getParameter("pageNum")) ? 1 : Integer.valueOf(request.getParameter("pageNum")));
        pageDto.setPageSize(StringUtils.isBlank(request.getParameter("pageSize")) ? 10 : Integer.valueOf(request.getParameter("pageSize")));
        return pageDto;
    }

    /**
     * 兼容偏移量与页码分页
     */
    public static void   startPage() {
        HttpServletRequest request = RequestContextHolder.getRequestAttributes() != null ? ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest() : null;
        if (StringUtils.isNotBlank(request.getParameter("offset"))) {
            PageHelper.offsetPage(Integer.valueOf(request.getParameter("offset")), Integer.valueOf(request.getParameter("limit")));
        } else {
            PageHelper.startPage(PageDto.getPage(request));
        }
    }
}
